<!doctype html>
<html lang="en">
<meta charset="UTF-8">
<body>
<style>
    .chat-group {
        background-color: rgb(73, 73, 73);
    }

    .chat {
        margin-top: 10px;
        background-color: #dbdede;
    }
</style>
<h1>聊天系统:</h1>
<div class="chat-group" id="chat-group">

</div>

<p>uid:<span id="uid"></span></p>
<p>信息:<input type="text" name="msg" id="msg"></p>
<button id="btn">发送</button>
<script src="https://m.acurd.com/template/home/default/js/vendor/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    // 1.建立连接
    var ws = new WebSocket("ws://" + location.host + "/ws")
    //接收消息
    ws.onmessage = function (event) {
        var data = event.data;
        //如果是消息 返回的是json
        if (!isJSON(data)) {
            $("#uid").text(data)
            return
        }
        addMsg(data)
    }
    ws.onopen = function (event) {
        console.log("连接上了");
    }
    //发送消息
    $("#btn").click(function () {
        var msg = $("#msg").val();
        var uid = $("#uid").text();
        var obj = {msg: msg, uid: uid}
        var json = JSON.stringify(obj)
        //发送json字符串
        ws.send(json)
    })
    function addMsg(data) {
        data = $.parseJSON(data)
        $("#chat-group").append("<div class=\"chat\">\n" +
            "        id: <span>" +
            data.uid +
            "</span>\n" +
            "        信息<span>" +
            data.msg +
            "</span>\n" +
            "    </div>")
        console.log(data.uid);
    }

    function isJSON(str) {
        if (typeof str == 'string') {
            try {
                var obj = JSON.parse(str);
                if (typeof obj == 'object' && obj) {
                    return obj;
                } else {
                    return false;
                }

            } catch (e) {
                console.log('error：' + str + '!!!' + e);
                return false;
            }
        }
        console.log('It is not a string!')
    }
</script>
</body>
</html>